import matplotlib.pyplot as plt
import numpy as np
from scipy import integrate


# 占空比为25%的非对称周期
def signal0_real(t, w, T):
    x = 0

    if -2 < t < -1:
        x = -1
    elif 1 <= t <= 2:
        x = 1
    elif -1 < t < 1:
        x = t

    y = x * np.exp(-1j * w * t)
    return np.real(y)


def signal0_imag(t, w, T):
    x = 0

    if -2 < t < -1:
        x = -1
    elif 1 <= t <= 2:
        x = 1
    elif -1 < t < 1:
        x = t

    y = x * np.exp(-1j * w * t)
    return np.imag(y)



T = 2
w = np.linspace(-10 * np.pi, 10 * np.pi, 1024)
N = len(w)
a1 = np.zeros(N)
err1 = np.zeros(N)
a2 = np.zeros(N)
err2 = np.zeros(N)

for n in range(N):
    a1[n], err1[n] = integrate.quad(signal0_real, -T, T, args=(w[n], T))
    a2[n], err2[n] = integrate.quad(signal0_imag, -T, T, args=(w[n], T))


A = a1 + 1j * a2

plt.rcParams['font.sans-serif'] = ['SimHei']  # 加上这一句就能在图表中显示中文
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号


plt.subplot(311)
plt.plot(w, np.sqrt(a1**2 + a2**2))
plt.ylabel('幅频特性')


plt.subplot(312)
plt.plot(w, a1)
plt.ylabel('实部')


plt.subplot(313)
plt.plot(w, a2)
plt.xlabel(r'$\omega$')
plt.ylabel('虚部')

plt.show()
